package com.mall.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

public class DBPool {
    public static String driver = "";
    public static String url = "";
    public static String username = "";
    public static String password = "";
    public static List<Connection> connList = new ArrayList<>();  //放连接的集合
    public static int poolSize = 10;  //连接数  10个数据库操作

    public static void init() {
        //加载配置文件
        Properties prop = new Properties();
        try {
            prop.load(DBPool.class.getClassLoader().getResourceAsStream("mysql.properties")); //加载到对象prop中
            driver = prop.getProperty("mysql.driver");  //根据键拿到值   com/mysql.cj.jdbc.Driver
            url = prop.getProperty("mysql.url");     //jdbc:mysql://127.0.0.1:3306/jf230510
            username = prop.getProperty("mysql.username");
            password = prop.getProperty("mysql.password");
            Class.forName(driver);
            System.out.println("mysql驱动加载成功（连接池版）！！！");
            //创建指定数量的连接，保存在集合里
            for (int i = 0; i < poolSize; i++) {
                connList.add(DriverManager.getConnection(url, username, password));
            }
//            System.out.println("初始化数据库连接池完毕！当前连接池数量为【" + poolSize + "】个");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //获取连接的方法（从池子里，拿连接来处理，移除一个。获取一个）
    public static Connection getConn() {
        Connection conn = null;

        if (connList.size() > 0) {  //里面有才能拿
            conn = connList.remove(0);
            //移除第一个，conn获得移除掉的对象，池子里少了一个
//            System.out.println("获取一个连接，当前连接池的连接数为【" + connList.size() + "】个");
        }
        return conn;
    }


    //关闭（归还 add）连接的方法
    public static void close(Connection conn) {

        if (conn != null) {
            connList.add(conn);
//            System.out.println("归还一个连接，当前连接池的连接数为【" + connList.size() + "】个");
        }

    }

}
